import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pandas as pd
from datetime import datetime, timedelta
from analysis.market_analyzer import MarketAnalyzer
from analysis.technical_indicators import TechnicalIndicators, IndicatorConfig
from analysis.ml_predictor import MLPredictor
from risk.risk_manager import RiskManager
from strategies.ml_enhanced_strategy import MLEnhancedStrategy
from config.settings import AnalysisConfig, RiskConfig

def main():
    # 配置
    analysis_config = AnalysisConfig()
    risk_config = RiskConfig()
    indicator_config = IndicatorConfig()
    
    # 初始化组件
    market_analyzer = MarketAnalyzer(analysis_config)
    risk_manager = RiskManager(risk_config)
    technical_indicators = TechnicalIndicators(indicator_config)
    ml_predictor = MLPredictor(model_dir='models')
    
    # 获取历史数据
    symbol = 'BTC/USDT'
    timeframe = '1h'
    start_time = datetime.now() - timedelta(days=30)
    
    print(f"获取{symbol}的历史数据...")
    market_data = market_analyzer.fetch_historical_data(
        symbol=symbol,
        timeframe=timeframe,
        start_time=start_time
    )
    
    # 训练机器学习模型
    print("训练机器学习模型...")
    market_data = technical_indicators.calculate_all(market_data)
    train_results = ml_predictor.train_models(market_data)
    
    print("\n模型训练结果:")
    for model_name, metrics in train_results.items():
        print(f"\n{model_name.upper()} 模型:")
        print(f"训练集 MSE: {metrics['train_mse']:.6f}")
        print(f"测试集 MSE: {metrics['test_mse']:.6f}")
        print(f"训练集 R2: {metrics['train_r2']:.6f}")
        print(f"测试集 R2: {metrics['test_r2']:.6f}")
        
    # 获取特征重要性
    print("\n特征重要性:")
    feature_importance = ml_predictor.get_feature_importance()
    for model_name, importance_df in feature_importance.items():
        print(f"\n{model_name.upper()} 模型特征重要性:")
        print(importance_df.head())
        
    # 初始化策略
    strategy_config = {
        'position_size': 0.1,
        'stop_loss': 0.02,
        'take_profit': 0.05,
        'max_positions': 3,
        'min_confidence': 0.6
    }
    
    strategy = MLEnhancedStrategy(
        market_analyzer=market_analyzer,
        risk_manager=risk_manager,
        technical_indicators=technical_indicators,
        ml_predictor=ml_predictor,
        config=strategy_config
    )
    
    # 模拟交易
    print("\n开始模拟交易...")
    for i in range(len(market_data) - 100, len(market_data)):
        current_data = market_data.iloc[:i+1]
        
        # 更新策略
        strategy.update(current_data)
        
        # 获取最新分析结果
        analysis = strategy.analyze_market(current_data)
        signal = strategy.generate_signals(analysis)
        
        # 打印交易信号
        if signal['signal'] != 'hold':
            print(f"\n时间: {current_data.index[-1]}")
            print(f"价格: {current_data['close'].iloc[-1]:.2f}")
            print(f"信号: {signal['signal'].upper()}")
            print(f"置信度: {signal['confidence']:.2f}")
            
    # 打印策略表现
    print("\n策略表现:")
    positions = risk_manager.positions
    print(f"当前持仓数量: {len(positions)}")
    print(f"总收益: {risk_manager.daily_pnl:.2f}")
    
if __name__ == '__main__':
    main()
